import 'package:casdon/app/config/env/env_provider.dart';
import 'package:casdon/app_providers.dart';
import 'package:casdon/core/network/api_client_provider.dart';
import 'package:casdon/core/network/i_api_client.dart';
import 'package:casdon/core/utils/json_parse_utils.dart';
import 'package:casdon/modules/me/data/api/browsing_life_history_api.dart';
import 'package:casdon/modules/me/data/api/browsing_recipe_history_api.dart';
import 'package:casdon/modules/me/data/api/fans_list_api.dart';
import 'package:casdon/modules/me/data/api/flower_list_api.dart';
import 'package:casdon/modules/me/data/api/oss_sts_api.dart';
import 'package:casdon/modules/me/data/api/service_channel_list_api.dart';
import 'package:casdon/modules/me/data/api/service_order_api.dart';
import 'package:casdon/modules/me/data/api/service_post_order_api.dart';
import 'package:casdon/modules/me/data/api/service_process_api.dart';
import 'package:casdon/modules/me/data/api/service_product_list_api.dart';
import 'package:casdon/modules/me/data/api/service_reqId_api.dart';
import 'package:casdon/modules/me/data/api/social_binded_list_api.dart';
import 'package:casdon/modules/me/data/api/user_center_api.dart';
import 'package:casdon/modules/me/data/api/user_info_api.dart';
import 'package:casdon/modules/me/data/repository/me_repository.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class MeRepositoryImpl extends MeRepository {
  // 字段类型也是抽象接口
  final IApiClient _apiClient;

  MeRepositoryImpl({required IApiClient apiClient}) : _apiClient = apiClient;

  @override
  Future<void> logOut() async {
    final _ = await _apiClient.post<void>('/auth-client/app/logout');
    return;
  }

  @override
  Future<ResponseUserCenterApi?> getUserCenterInfo() async {
    final res = await _apiClient.getTyped<ResponseUserCenterApi>(
      '/client-operation/life/user/center',
      fromJsonT: (json) =>
          ResponseUserCenterApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<ResponseUserInfoApi?> getUserInfo() async {
    final res = await _apiClient.getTyped<ResponseUserInfoApi>(
      '/client-user/user/info',
      fromJsonT: (json) =>
          ResponseUserInfoApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<void> putModifyUserInfo({
    required String? nickName,
    required String? sex, //（0男 1女 2未知）
    required String? birthday,
    required int? avatar,
  }) async {
    final _ = await _apiClient.put<void>(
      '/client-user/user/modify/info',
      data: {
        "nickName": nickName,
        "sex": sex,
        "birthday": birthday,
        "avatar": avatar,
      },
    );
    return;
  }

  @override
  Future<List<ResponseServiceReqIdApi>?> getServiceReqIdList() async {
    final res = await _apiClient.getTyped<List<ResponseServiceReqIdApi>>(
      '/client-user/sale/orderList',
      fromJsonT: (json) => parseList(json, ResponseServiceReqIdApi.fromJson),
    );
    return res?.data;
  }

  @override
  Future<ResponseServiceOrderDataApi?> getServiceOrderList({
    required String reqId,
  }) async {
    final env = getProvider(environmentProvider);
    final res = await _apiClient.getTyped<ResponseServiceOrderDataApi>(
      '${env.ry_url}/api/dynamic/new_srv_workorder',
      query: {'\$filter': "new_srv_workorderid eq $reqId"},
      fromJsonT: (json) =>
          ResponseServiceOrderDataApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<SRVWorkOrderResponse?> getServiceProcess({
    required String reqId,
  }) async {
    final env = getProvider(environmentProvider);
    final res = await _apiClient.getTyped<SRVWorkOrderResponse>(
      '${env.ry_url}/api/dynamic/new_srv_activity',
      query: {
        '\$filter': "regardingobjectid/id eq $reqId",
        '\$orderby': 'createdon asc',
        '\$select':
            'subject,regardingobjectidname,new_type,createdon,regardingobjectid',
      },
      fromJsonT: (json) =>
          SRVWorkOrderResponse.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<String?> postServiceOrder({
    required ServicePostOrder postOrder,
  }) async {
    final env = getProvider(environmentProvider);
    final res = await _apiClient.postTyped<String>(
      '${env.ry_url}/api/dynamic/new_srv_workorder/save',
      data: postOrder.toJson(),
      fromJsonT: (json) => json.toString(),
    );
    return res?.data;
  }

  @override
  Future<SRVWorkOrderResponse?> postServiceOrderReqId({
    required String orderReqId,
  }) async {
    final res = await _apiClient.postTyped<SRVWorkOrderResponse>(
      '/client-user/sale/saveOrder',
      data: {'orderId': orderReqId},
      fromJsonT: (json) =>
          SRVWorkOrderResponse.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<ResponseServiceChannelListApi?> getSalesChannels() async {
    final env = getProvider(environmentProvider);
    final res = await _apiClient.getTyped<ResponseServiceChannelListApi>(
      '${env.ry_url}/api/dynamic/casdon_sales_channels',
      query: {'\$select': "casdon_name,casdon_channel_code"},
      fromJsonT: (json) =>
          ResponseServiceChannelListApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<ResponseServiceProductListApi?> getProducts() async {
    final env = getProvider(environmentProvider);
    final res = await _apiClient.getTyped<ResponseServiceProductListApi>(
      '${env.ry_url}/api/dynamic/product',
      query: {
        '\$select':
            "new_productgroupidname,new_productmodule_idname,productnumber,name",
        '\$filter': "new_itemtype eq 1",
      },
      fromJsonT: (json) =>
          ResponseServiceProductListApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<List<ResponseSocialBindedListApi>?> getSocialList() async {
    final res = await _apiClient.getTyped<List<ResponseSocialBindedListApi>?>(
      '/auth-client/social/list',
      fromJsonT: (json) =>
          parseList(json, ResponseSocialBindedListApi.fromJson),
    );
    return res?.data;
  }

  @override
  Future<void> postSocialBind({
    required String source,
    required String code,
  }) async {
    final res = await _apiClient.postTyped<ResponseServiceProductListApi>(
      '/auth-client/social/bind',
      data: {"source": source, "code": code},
      fromJsonT: (json) =>
          ResponseServiceProductListApi.fromJson(json as Map<String, dynamic>),
    );
    return;
  }

  @override
  Future<void> delSocialBind(String socialId) async {
    final res = await _apiClient.delete<void>(
      '/auth-client/unbind/{id}',
      pathParams: {'id': socialId},
    );
    return;
  }

  @override
  Future<void> postUpdatePwd(String userName, String pwd) async {
    final res = await _apiClient.post<void>(
      '/auth-client/updatePwd',
      data: {'userName': userName, 'newPassword': pwd},
    );
    return;
  }

  @override
  Future<Map<String, dynamic>> getAppVersionInfo(
    String platform,
    String currentVer,
  ) async {
    final res = await _apiClient.get<Map<String, dynamic>>(
      '/client-product/version/v1/app',
      query: {
        'platform': platform,
        'currentVer': currentVer,
        'releasePlatform': 1,
      },
    );
    return Map<String, dynamic>.from(res!);
  }

  @override
  Future<ResponseFlowerListApi?> getFlowerList(
    int pageNum,
    int pageSize,
  ) async {
    final res = await _apiClient.getTyped<ResponseFlowerListApi?>(
      '/client-operation/life/user/follow/list',
      query: {
        "pageNum": pageNum,
        "pageSize": pageSize,
        "orderByColumn": "followTime",
        "isAsc": "desc",
      },
      fromJsonT: (json) =>
          ResponseFlowerListApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<ResponseFansListApi?> getFansList(int pageNum, int pageSize) async {
    final res = await _apiClient.getTyped<ResponseFansListApi?>(
      '/client-operation/life/user/fans/list',
      query: {
        "pageNum": pageNum,
        "pageSize": pageSize,
        "orderByColumn": "followTime",
        "isAsc": "desc",
      },
      fromJsonT: (json) =>
          ResponseFansListApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<ResponseOssStsApi?> getOSSStsToken(String userId) async {
    final res = await _apiClient.getTyped<ResponseOssStsApi?>(
      '/client-product/oss/getStsToken',
      query: {'fileType': "image", "type": "cloud-app", 'userId': userId},
      fromJsonT: (json) =>
          ResponseOssStsApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  @override
  Future<Map<String, dynamic>?> getTuyaDeviceInfo({
    required String devId,
  }) async {
    final res = await _apiClient.getTypedNOBase<Map<String, dynamic>>(
      '/client-product/tuya/getDeviceInfo/{devId}',
      pathParams: {'devId': devId},
      fromJsonT: (json) => json as Map<String, dynamic>,
    );
    return res;
  }

  // 获取菜谱浏览记录
  @override
  Future<ResponseBrowsingRecipeHistoryApi?> getRecipeBrowsingHistory({
    required final int pageNum,
    required final int pageSize,
  }) async {
    final res = await _apiClient.getTyped<ResponseBrowsingRecipeHistoryApi>(
      '/client-operation/recipe/user/getUserBrowses',
      query: {
        "pageNum": pageNum,
        "pageSize": pageSize,
        "orderByColumn": "createTime",
        "isAsc": "desc",
      },
      fromJsonT: (json) => ResponseBrowsingRecipeHistoryApi.fromJson(
        json as Map<String, dynamic>,
      ),
    );
    return res?.data;
  }

  // 获取生活圈浏览记录
  @override
  Future<ResponseBrowsingLifeHistoryApi?> getLifeBrowsingHistory({
    required final int pageNum,
    required final int pageSize,
  }) async {
    final res = await _apiClient.getTyped<ResponseBrowsingLifeHistoryApi>(
      '/client-operation/life/user/view/list',
      query: {"pageSize": pageSize, "pageNum": pageNum},
      fromJsonT: (json) =>
          ResponseBrowsingLifeHistoryApi.fromJson(json as Map<String, dynamic>),
    );
    return res?.data;
  }

  // 关注/取消关注用户
  @override
  Future<void> followUser({
    required String followUuid,
    required String flag,
  }) async {
    await _apiClient.post<void>(
      '/client-operation/life/topic/follow',
      data: {"followUuid": followUuid, "flag": flag},
    );
    return;
  }
}

final meRepositoryProvider = Provider<MeRepository>(
  (ref) => MeRepositoryImpl(apiClient: ref.read(apiClientProvider)),
);
